package com.menhai.personmanagement.utils;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.menhai.personmanagement.entity.MbPopulation;
import lombok.val;

import java.text.SimpleDateFormat;
import java.util.*;

public class CalculationTool {

    public static List getAgeAndSex(List<MbPopulation> list){
        list.forEach(val -> {
            val.setAge(getAgeAndSex(val.getIdnumber()).get("age").toString());
        });
        return list;
    }

    public static MbPopulation getAgeAndSexobject(MbPopulation mbPopulation){
        mbPopulation.setAge(getAgeAndSex(mbPopulation.getIdnumber()).get("age").toString());
        return mbPopulation;
    }

    public static Page getAgeAndSex(Page<MbPopulation> page){
        page.getRecords().forEach(val -> {
            val.setAge(getAgeAndSex(val.getIdnumber()).get("age").toString());
        });
        return page;
    }

    public static Map<String, Object> getAgeAndSex(String CardCode){
        Map<String, Object> map = new HashMap<String, Object>();
        String year = CardCode.substring(6).substring(0, 4);// 得到年份
        String yue = CardCode.substring(10).substring(0, 2);// 得到月份
        String day=CardCode.substring(12).substring(0,2);//得到日
        String sex;
        if (Integer.parseInt(CardCode.substring(16).substring(0, 1)) % 2 == 0) {// 判断性别
            sex = "女";
        } else {
            sex = "男";
        }


        int timeage = -1;
        try {
            String smdate = year + "-" + yue + "-" + day;
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            String bdate = format.format(new Date());

            Calendar cal = Calendar.getInstance();
            cal.setTime(format.parse(smdate));
            long time1 = cal.getTimeInMillis();
            cal.setTime(format.parse(bdate));
            long time2 = cal.getTimeInMillis();
            long between_days = (time2 - time1) / (1000 * 3600 * 24);
            timeage = (int)Math.floor(between_days / 365.2422);
        }catch (Exception e){
            e.printStackTrace();
        }

//        Date date = new Date();// 得到当前的系统时间
//        String fyear = format.format(date).substring(0, 4);// 当前年份
//        String fyue = format.format(date).substring(5, 7);// 月份
//        // String fday=format.format(date).substring(8,10);
//        int age = 0;
//        if (Integer.parseInt(yue) <= Integer.parseInt(fyue)) { // 当前月份大于用户出身的月份表示已过生
//            age = Integer.parseInt(fyear) - Integer.parseInt(year) + 1;
//        } else {// 当前用户还没过生
//            age = Integer.parseInt(fyear) - Integer.parseInt(year);
//        }
        map.put("sex", sex);
//        map.put("age", age);
        map.put("age", timeage);
        return map;
    }
}
